package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavoMapper;  // 修正导入路径
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 套餐业务实现
 */
@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    
    @Autowired
    private SetmealMapper setmealMapper;
    
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    
    @Autowired
    private DishMapper dishMapper;
    
    @Autowired
    private DishFlavoMapper dishFlavoMapper;  // 修正变量名为 dishFlavorMapper
    
    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }
    
    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
    
    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDTO
     */
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        
        // 向套餐表插入数据
        setmealMapper.insert(setmeal);
        
        // 获取生成的套餐id
        Long setmealId = setmeal.getId();
        
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        
        // 保存套餐和菜品的关联关系
        setmealDishMapper.insertBatch(setmealDishes);
    }
    
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        
        List<DishVO> dishVOList = new ArrayList<>();
        
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            
            // 根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavoMapper.getByDishId(d.getId());  // 使用修正后的变量名
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        
        return dishVOList;
    }
    /**
     * 分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        int pageNum = setmealPageQueryDTO.getPage();
        int pageSize = setmealPageQueryDTO.getPageSize();
        
        PageHelper.startPage(pageNum, pageSize);
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }
    /**
     * 批量删除套餐
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id -> {
            Setmeal setmeal = setmealMapper.getById(id);
            if(StatusConstant.ENABLE == setmeal.getStatus()){
                //起售中的套餐不能删除
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });
        
        ids.forEach(setmealId -> {
            //删除套餐表中的数据
            setmealMapper.deleteById(setmealId);
            //删除套餐菜品关系表中的数据
            setmealDishMapper.deleteBySetmealId(setmealId);
        });
    }
    /**
     * 根据id查询套餐和套餐菜品关系
     *
     * @param id
     * @return
     */
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.getById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
        
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        
        return setmealVO;
    }
    
    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        
        // 确保所有字段已正确赋值
        if (setmeal.getName() == null) {
            setmeal.setName("默认套餐名称"); // 设置默认值或从数据库查询原值
        }
        if (setmeal.getPrice() == null) {
            setmeal.setPrice(BigDecimal.ZERO); // 设置默认值或从数据库查询原值
        }
        if (setmeal.getCategoryId() == null) {
            setmeal.setCategoryId(1L); // 设置默认值或从数据库查询原值
        }
        if (setmeal.getDescription() == null) {
            setmeal.setDescription("默认描述"); // 设置默认值或从数据库查询原值
        }
        if (setmeal.getImage() == null) {
            setmeal.setImage("默认图片路径"); // 设置默认值或从数据库查询原值
        }
        
        // 1、修改套餐表，执行update
        setmealMapper.update(setmeal);
        
        // 套餐id
        Long setmealId = setmealDTO.getId();
        
        // 2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteBySetmealId(setmealId);
        
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        // 3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.insertBatch(setmealDishes);
    }
    
    /**
     * 套餐起售、停售
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        // 查询原始数据
        Setmeal setmeal = setmealMapper.getById(id);
        if (setmeal == null) {
            throw new RuntimeException("套餐不存在");
        }
        
        // 只更新 status 字段
        setmeal.setStatus(status);
        setmealMapper.update(setmeal);
        
        // 如果是停售操作，还需要将包含当前套餐的菜品也停售
        if (status == StatusConstant.DISABLE) {
            List<Long> setmealIds = new ArrayList<>();
            setmealIds.add(id);
            List<Long> dishIds = setmealDishMapper.getDishIdsBySetmealIds(setmealIds);
            if (dishIds != null && dishIds.size() > 0) {
                for (Long dishId : dishIds) {
                    // 查询菜品原始数据
                    Dish dish = dishMapper.getById(dishId);
                    if (dish != null) {
                        // 更新所有字段，而不仅仅是 status
                        dish.setStatus(StatusConstant.DISABLE);
                        dishMapper.updateDish(dish);
                    }
                }
            }
        }
    }
    
    
}
